package com.nys.cqhttp.util;

import java.io.BufferedReader;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.nys.cqhttp.param.MessageParam;
import org.apache.commons.lang3.StringUtils;

/**
 * MsgHandlerUtil
 *
 * @author nysheng
 * @version 1.0.0
 * @date 2021/12/27 14:24
 */
public class RequestUtil {

  /**
   * @author nysheng
   * @description 解析request请求中的消息内容
   * @date 2021/12/27 14:25
   * @param request
   * @return com.nys.cqhttp.dto.messageParam
   * @version 1.0.0
   */
  public static MessageParam getMessageParam(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder();
    try (BufferedReader bufferedReader = new BufferedReader(request.getReader())) {
      String str;
      while ((str = bufferedReader.readLine()) != null) {
        sb.append(str);
      }
    } catch (Exception e) {
      return MessageParam.builder().build();
    }
    Map<String, Object> map = JSONObject.parseObject(sb.toString(), Map.class);

    String post_type = map.get("post_type").toString();

    if (StringUtils.isNotEmpty(post_type)) {
      if ("request".equals(post_type)){
        System.out.println(sb.toString());
      }
      switch (post_type) {
        case "message":
          return getMessageParam(map);
        case "notice":
          return getNotice(map);
        case "request":
          return getRequest(map);
      }
    }
    return MessageParam.builder().build();
  }

  public static MessageParam getMessageParam(Map<String, Object> map) {
    JSONObject senderMap = (JSONObject) map.get("sender");

    return MessageParam.builder()
        .selfId(String.valueOf(map.get("self_id")))
        .message(String.valueOf(map.get("raw_message")))
        .senderId(String.valueOf(senderMap.get("user_id")))
        .groupId(String.valueOf(map.get("group_id")))
        .messageType(String.valueOf(map.get("message_type")))
            .messageId(String.valueOf(map.get("message_id")))
        .build();
  }

  public static MessageParam getRequest(Map<String, Object> map) {
    return MessageParam.builder()
        .selfId(String.valueOf(map.get("self_id")))
        .message(String.valueOf(map.get("sub_type")))
        .senderId(String.valueOf(map.get("user_id")))
        .groupId(String.valueOf(map.get("group_id")))
        .operatorId(String.valueOf(map.get("comment")))
        .messageType(String.valueOf(map.get("request_type")))
        .flag(String.valueOf(map.get("flag")))
        .build();
  }

  public static MessageParam getNotice(Map<String, Object> map) {

    return MessageParam.builder()
        .selfId(String.valueOf(map.get("self_id")))
        .message(String.valueOf(map.get("sub_type")))
        .senderId(String.valueOf(map.get("user_id")))
        .groupId(String.valueOf(map.get("group_id")))
        .operatorId(String.valueOf(map.get("operator_id")))
        .messageType("group")
        .build();
  }
}
